from flask import Blueprint, render_template, jsonify, request
from models.entity.gateway import Gateway
from appserver import db_store, execute_sql, sql_row_to_dict
import json
import uuid
import datetime
from utils.result import Result

mod = Blueprint('iot_gateway', __name__, url_prefix='/iot/gateway', template_folder='templates',
                static_folder='static')


@mod.route("/", methods=["GET"])
def iot_gateway_index(*args, **kargs):
    return render_template('/admin/iot/iot_gateway_index.html', **locals())


@mod.route("/getListJson", methods=["GET", "POST"])
def gateway_get_list_json(*args, **kargs):
    result = []
    # gws = execute_sql("select *, (select count(*) from iot_sensors where clientid = a.clientid) as sensor_num from iot_gateway as a")
    gws = execute_sql(
        "select *, (select count(*) from sensors where clientid = a.clientid) as sensor_num from iot_gateway as a")
    print(111,gws)
    for item in gws:
        print('item', item)
        result.append(sql_row_to_dict(item))
    print(222,result)
    return jsonify(result)

@mod.route("/editGateway", methods=["GET", "POST"])
def editGateway(*args, **kargs):
    if request.method == 'POST':
        msg = ''
        # data = json.loads(request.data.decode("utf-8"))
        print(222,request.data)   # b ''
        print(333,request.data.decode("utf-8")) # None 不能编码
        data = json.loads(request.data.decode("utf-8"))
        print(11111111,data)
        if data['id'] > 0:
            print('if里面')
            if data.get('id') == Gateway.id:
                entity = Gateway().query.filter(Gateway.id == data['id']).first()
                msg = '编辑数据采集网关'
            else:
                entity = Gateway()
                msg = '新建数据采集网关'
                entity.name = data['name']
                entity.code = data['code']
                entity.clientid = str(uuid.uuid1())
                entity.is_superuser = 0
                entity.created = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                entity.id = data['id']
            # entity.name = data['name']
            # entity.code = data['code']
            # entity.type = data['type']
            # entity.icon = data['icon']
            # entity.username = data['username']
            # entity.password = data['password']
            # entity.salt = data['salt']
            # entity.dis_order = data['dis_order']
            # entity.status = data['status']
            # entity.description = data['description']
            if entity.save():
                return Result(1, msg + '成功.', data=data).ToJson()
            else:
                return Result(0, msg + '失败.', data=data).ToJson()
    else:
        return "3333"


# @mod.route("/editGateway", methods=["GET", "POST"])
# def editGateway(*args, **kargs):
#     if request.method == 'POST':
#         msg = ''
#         data = json.loads(request.data.decode("utf-8"))
#         print('data', data)
#         if data['id'] == Gateway.id:
#             entity = Gateway().query.filter(Gateway.id == data['id']).first()
#             msg = '编辑数据采集网关'
#         else:
#             entity = Gateway()
#             msg = '新建数据采集网关'
#             entity.clientid = str(uuid.uuid1())
#             entity.is_superuser = 0
#             entity.created = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#         entity.id = data['id']
#         entity.name = data['name']
#         entity.code = data['code']
#         # entity.type = data['type']
#         # entity.icon = data['icon']
#         # entity.username = data['username']
#         # entity.password = data['password']
#         # entity.salt = data['salt']
#         # entity.dis_order = data['dis_order']
#         # entity.status = data['status']
#         # entity.description = data['description']
#         if entity.save():
#             return Result(1, msg + '成功.', data=data).ToJson()
#         else:
#             return Result(0, msg + '失败.', '').ToJson()
#     else:
#         return 'get'

@mod.route("/delGateway", methods=["GET", "POST"])
def delGateway(*args, **kargs):
    if request.method == 'POST':
        msg = ''
        data = json.loads(request.data.decode("utf-8"))
        entity = Gateway().query.filter(Gateway.id == data['id']).first()
        if entity.delete():
            return Result(1, '删除数据采集网关成功.', '').ToJson()
        else:
            return Result(0, '删除数据采集网关失败.', '').ToJson()
    else:
        return 'get'
